package com.wms.controller;


import com.wms.constant.UserConstant;
import com.wms.pojo.Result;
import com.wms.pojo.User;
import com.wms.service.IUserService;
import com.wms.utils.Md5Util;
import jakarta.validation.constraints.Pattern;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.time.LocalDateTime;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author author
 * @since 2024-06-13
 */
@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {
    @Autowired
    private IUserService userService;
    /**
     * 用户注册
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/register")
    public Result register(@Pattern(regexp = "^\\S{5,20}$") String username,
                           @Pattern(regexp = "^\\S{5,20}$")String password){
        log.info("用户注册：{},{}",username,password);
        //查询用户是否存在
        User user = userService.getByUsername(username);
        if (user != null){
            //存在，返回已存在
            return Result.error(UserConstant.REGISTER);
        }
        //密码加密
        String md5Password = Md5Util.getMD5String(password);
        //不存在，数据加入数据库,返回注册成功
        User newUser = User.builder().username(username)
                .password(md5Password)
                .createTime(LocalDateTime.now())
                .updateTime(LocalDateTime.now())
                .build();
        userService.save(newUser);
        return Result.success();
    }
}
